package com.sj;

import com.dom.DomReader;
import com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;

public class PhoneDom {
    /**上机1：
     * 创建保存手机品牌为华为，型号为P90
     * 手机品牌为苹果，型号为iPhone Z和iPhone ZL等手机信息的xml文档
     * 使用Dom解析读取xml文档信息并显示
     */
    // 添加
    @Test
    public void testAdd()throws Exception{
        //得到dom解析器的工厂
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        //从dom工厂获得dom解析器
        DocumentBuilder db=dbf.newDocumentBuilder();
        //解析xml文档，得到一个Document对象，即dom树
        Document doc=db.parse("src/main/resources/Phone_02.xml");
        //创建Brand节点
        Element brandElemnet=doc.createElement("Brand");
        brandElemnet.setAttribute("name","华为");
        //创建Type节点
        Element typeElement=doc.createElement("Type");
        typeElement.setAttribute("name","NoteX");

        Element brandElemnet2=doc.createElement("Brand");
        brandElemnet2.setAttribute("name","苹果");
        //创建Type节点
        Element typeElement2=doc.createElement("Type");
        typeElement2.setAttribute("name","iPhone 11");
        Element typeElement3=doc.createElement("Type");
        typeElement3.setAttribute("name","iPhone xs max");


        //添加父子关系
        brandElemnet.appendChild(typeElement);
        brandElemnet2.appendChild(typeElement2);
        brandElemnet2.appendChild(typeElement3);
        Element phoneElement=(Element) doc.getElementsByTagName("PhoneInfo").item(0);
        phoneElement.appendChild(brandElemnet);
        phoneElement.appendChild(brandElemnet2);
        //保存xml文件
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        Transformer transformer=transformerFactory.newTransformer();
        DOMSource domSource=new DOMSource(doc);
        //设置编码类型
        transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
        StreamResult result=new StreamResult(new FileOutputStream("src/main/resources/Phone_02.xml"));
        transformer.transform(domSource,result);
    }


    //使用Dom解析读取xml文档信息并显示
    @Test
    public void testInfo()throws Exception{
        //得到Dom解析器的工厂实例
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        //从DOM工厂获得DOM解析器
        DocumentBuilder db=dbf.newDocumentBuilder();
        //解析xml文档，得到一个Document对象
        Document doc=db.parse("src/main/resources/Phone_02.xml");
        //获取根节点
        Element phoneInfo=doc.getDocumentElement();
        //用标签名获取节点列表
        NodeList brandList=phoneInfo.getElementsByTagName("Brand");
        for(int i=0;i< brandList.getLength();i++){
          Element brandEl=(Element) brandList.item(i);
          //name属性
            String nameAttr=brandEl.getAttribute("name");
            //Type集合
            NodeList typeList=brandEl.getElementsByTagName("Type");
            for(int j=0;j<typeList.getLength();j++){
                Element typeEl=(Element) typeList.item(i);
                String typeName=typeEl.getAttribute("name");
                System.out.println("手机品牌："+nameAttr+"，型号："+typeName);
            }
        }
    }


    /**
     * 上机2：
       在xml文档中添加品牌为"三星"，型号为"NoteX"的节点
     * 在xml文档中品牌信息"三星"修改为"SAMSUNG"
     * 在xml文档中将品牌信息为"SAMSUNG"的节点删除
     * 修改后的DOM树保存到xml文档
     */

    //在xml文档中添加品牌为"三星"，型号为"NoteX"的节点
    @Test
    public void testAddNode()throws Exception{
        //得到DOM解析器的工厂实例
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        //从DOM工厂获得DOM解析器
        DocumentBuilder db=dbf.newDocumentBuilder();
        //解析xml文档，得到一个Document对象，即DOM树
        Document doc=db.parse("src/main/resources/Phone_02.xml");
        //创建Brand节点
        Element branEl=doc.createElement("Brand");
        branEl.setAttribute("name","三星");
        //创建Type节点
        Element typeEl=doc.createElement("Type");
        typeEl.setAttribute("name","NoteX");
        //添加父子关系
        branEl.appendChild(typeEl);
        //获取PhoneInfo节点
        Element phoneInfoEl=(Element) doc.getElementsByTagName("PhoneInfo").item(0);
        //把branEl标签添加进去
        phoneInfoEl.appendChild(branEl);

        //保存xml文件
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        Transformer transformer=transformerFactory.newTransformer();
        DOMSource domSource=new DOMSource(doc);
        //设置编码类型
        transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
        StreamResult result=new StreamResult(new FileOutputStream("src/main/resources/Phone_02.xml"));
        //把DOM树转为xml文件
        transformer.transform(domSource,result);
    }


    //在xml文档中品牌信息"三星"修改为"SAMSUNG"
    @Test
    public void testUpdate()throws Exception{
        //工厂
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        //DOM解析器
        DocumentBuilder db=dbf.newDocumentBuilder();
        //解析xml文档
        Document doc=db.parse("src/main/resources/Phone_02.xml");
        //找到修改节点
        NodeList list=doc.getElementsByTagName("Brand");
        for(int i=0;i< list.getLength();i++){
            Element brandEl=(Element) list.item(i);
            String brandName=brandEl.getAttribute("name");
            if(brandName.equals("三星")){
                brandEl.setAttribute("name","SAMSUNG");
            }
        }
        //保存文件
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        Transformer transformer=transformerFactory.newTransformer();
        DOMSource domSource=new DOMSource(doc);
        //设置编码类型
        transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
        StreamResult result=new StreamResult(new FileOutputStream("src/main/resources/Phone_02.xml"));
        //把DOM树转为xml文件
        transformer.transform(domSource,result);
    }


    //在xml文档中将品牌信息为"SAMSUNG"的节点删除
    @Test
    public void testDelete()throws Exception{
        //工厂
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        //DOM解析器
        DocumentBuilder db=dbf.newDocumentBuilder();
        //解析xml文档
        Document doc=db.parse("src/main/resources/Phone_02.xml");
        //找到要删除的节点
        NodeList list=doc.getElementsByTagName("Brand");
        for(int i=0;i< list.getLength();i++){
            Element brandEl=(Element) list.item(i);
            String brandName=brandEl.getAttribute("name");
            if(brandName.equals("SAMSUNG")){
                brandEl.getParentNode().removeChild(brandEl); //找到父节点下面的所有子节点进行删除，包括父节点本身
            }
        }
        //保存文件
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        Transformer transformer=transformerFactory.newTransformer();
        DOMSource domSource=new DOMSource(doc);
        transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
        StreamResult result=new StreamResult(new FileOutputStream("src/main/resources/Phone_02.xml"));
        //把DOM树转为xml文件
        transformer.transform(domSource,result);
    }
}
